package com.yanqu.road.server.gameplayer.module.activity.game2048;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.game.ActivityPageantInfo;
import com.yanqu.road.entity.activity.game.PageantBeautyDetail;
import com.yanqu.road.entity.activity.game.PageantDetail;
import com.yanqu.road.entity.activity.game.PageantInfo;
import com.yanqu.road.entity.activity.game.config.*;
import com.yanqu.road.entity.activity.game.result.RankingDetailsResult;
import com.yanqu.road.entity.activity.game.result.UserPageantDataResult;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.log.LogPageantClearLog;
import com.yanqu.road.entity.player.UserBeauty;
import com.yanqu.road.entity.player.UserPageantData;
import com.yanqu.road.logic.bussiness.activity.PageantBussiness;
import com.yanqu.road.logic.rank.RankListModel;
import com.yanqu.road.pb.pageant.PageantProto;
import com.yanqu.road.pb.rank.RankProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.BagModule;
import com.yanqu.road.server.gameplayer.module.player.BeautyModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.GamePageantMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.cross.CrossDataMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.rank.ActivityRankMgr;
import com.yanqu.road.server.pb.PageantPb;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigInteger;
import java.util.*;

public class PageantModule extends GeneralModule {

    private static Logger logger = LogManager.getLogger(PageantModule.class.getName());

    Map<Integer, UserPageantData> userPageantDataMap;

    /**
     * 用户登陆加载
     *
     * @param player
     */
    public PageantModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        //获取用户游戏数据
        userPageantDataMap = PageantBussiness.getUserGameInfo(player.getUserId());
        return true;
    }


    @Override
    public boolean afterLoadData() {
        return false;
    }

    @Override
    public boolean saveData() {
        for (UserPageantData userPageantData : userPageantDataMap.values()) {
            if (userPageantData.isInsertOption()) {
                PageantBussiness.addUserInfo(userPageantData);
            } else if (userPageantData.isUpdateOption()) {
                PageantBussiness.updateUserInfo(userPageantData);
            }
        }
        return true;
    }

    /**
     * 绑定美女
     * 用户初始化数据
     */
    public UserPageantDataResult initGameData(int activityId, int beautyId) {
        //是否是第一次进入活动
        UserPageantDataResult result = new UserPageantDataResult();
        result.setRet(0);
        UserPageantData gameData = getUserPageantData(activityId);
        long nowTime = System.currentTimeMillis();

        if (gameData.getBeautyId() > 0) {
            result.setRet(GameErrorCode.E_PAGEANT_BIND_ALREADY);
            return result;
        }

        gameData.setBeautyId(beautyId);
        gameData.setLastUpdateTime(nowTime);
        result.setUserPageantData(gameData);
        return result;
    }

    public void resetOneDay() {
        try {
            ActivityInfo activityInfo = GamePageantMgr.getActivityInfo();
            if (activityInfo != null && ActivityMgr.activityInShowTime(activityInfo)) {
                UserPageantData gameData = getUserPageantData(activityInfo.getActivityId());
                if (!DateHelper.isToday(new Date(gameData.getResetTime()))) {
                    gameData.setTodayGetMoney(0);
                    gameData.setResetTime(System.currentTimeMillis());
                    //通知客户端更新
                    player.sendPacket(Protocol.U_PAGEANT_REFRESH_TODAYMONEY,PageantPb.parsePageantBaseRespMsg(gameData));
                }
            }
        } catch (Exception ex) {
            log.error(ex);
        }
    }

    /**
     * 获取玩家信息
     */
    public UserPageantData getUserPageantData(int activityId) {
        ActivityInfo activityInfo = GamePageantMgr.getActivityInfo();
        if (activityInfo != null && ActivityMgr.activityInShowTime(activityInfo)) {
            if (!userPageantDataMap.containsKey(activityId)) {
                long nowTime = System.currentTimeMillis();
                UserPageantData gameData = new UserPageantData();
                gameData.setUserId(player.getUserId());
                gameData.setBeautyId(0);
                gameData.setActivityId(activityId);
                gameData.setPhysicalStrength(GamePageantMgr.getStrengthConfig().getMaxStrength());//初始化体力值
                gameData.setScore(0);
                gameData.setSingleHighScore(0);
                gameData.setHighScore(0);
                gameData.setPaint(getNewPaint());
                gameData.setStrengthTime(nowTime);
                gameData.setLockBeauty(getNewLockBeauty());
                gameData.setLastUpdateTime(nowTime);
                int chongPai = GamePageantMgr.getGoodsTimesChongPai();
                int xiaochu = GamePageantMgr.getGoodsTimesXiaochu();
                gameData.setGoodsTimes(chongPai + "|" + xiaochu);//重排|消除
                gameData.setTodayGetMoney(0);
                gameData.setResetTime(System.currentTimeMillis());
                gameData.setInsertOption();
                userPageantDataMap.put(activityId, gameData);
            }
        }
        return userPageantDataMap.get(activityId);
    }


    @Override
    public void afterLogin() {
        if (SystemOpenMgr.systemOpen(player, eSystemId.Pageant.getValue())) {
            syncActivity();
        }
    }


    /**
     * 同步活动数据
     */
    public void syncActivity() {
        //正在执行的活动消息
        ActivityInfo activityInfo = GamePageantMgr.getActivityInfo();
        if (activityInfo != null && ActivityMgr.activityInShowTime(activityInfo)) {
            GoodsConfig config = GamePageantMgr.getGoodsConfig();
            List<BeautyConfig> beautyConfigs = getPicture();
            PageantProto.PageantActivityDetailMsg.Builder detailMsg = PageantPb.parsePageantActivityMsg(player.getUserInfo().getLanguage(), activityInfo, getUserPageantData(activityInfo.getActivityId()), config, beautyConfigs);
            player.sendPacket(Protocol.U_PAGEANT_INIT_GAME, detailMsg);
            autoUseActivityGoods(activityInfo);
        }
    }

    /**
     * 开始游戏  玩家,方向,游戏类型
     */
    public UserPageantDataResult playGame(int activityId, int direction, int type) {
        UserPageantDataResult resultBack = new UserPageantDataResult();
        UserPageantData data = getUserPageantData(activityId);
        resultBack.setReward("");//本次合成奖励，只作为传递数据使用
        resultBack.setRet(0);
        resultBack.setUserPageantData(data);
        if (data.getBeautyId() <= 0) {
            resultBack.setRet(GameErrorCode.E_PAGEANT_BEAUTY_EMPTY);
            return resultBack;
        }

        try {
            addPower(data);//到期增加
            int myPower = data.getPhysicalStrength();
            if (type == 1) {
                if ((myPower - 1) < 0) {
                    //体力不够
                    resultBack.setRet(GameErrorCode.E_PAGEANT_STRENGTH_NOT_ENOUGH);
                    return resultBack;
                }
            } else if (type == 2) {
                if ((myPower - 4) < 0) {
                    //体力不够
                    resultBack.setRet(GameErrorCode.E_PAGEANT_STRENGTH_NOT_ENOUGH);
                    return resultBack;
                }
            } else if (type == 3) {
                if ((myPower - 16) < 0) {
                    //体力不够
                    resultBack.setRet(GameErrorCode.E_PAGEANT_STRENGTH_NOT_ENOUGH);
                    return resultBack;
                }
            }
            PageantInfo pageantInfo = changeData(data, direction, activityId);
            if (pageantInfo.isChange()) {
                //添加新格子
                List<Integer> addCreateCreate = new ArrayList<>(); // 记录生成美女奖励：0积分，1选美币
                List<PageantDetail> result = addTile(type, pageantInfo.getPagentDetails(), addCreateCreate);
                //加积分、选美币
                if (type == 2 || type == 3) {
                    addScoreAndMoney(data, addCreateCreate.get(0), addCreateCreate.get(1));
                }
                //判断是否解锁增加亲密缘分
                String lockBeauty = data.getLockBeauty();
                List<PageantBeautyDetail> lockList = JSONObject.parseArray(lockBeauty, PageantBeautyDetail.class);

                boolean isAdd = checkEffectFirstMerge(lockList, result, data);
                if (isAdd) {
                    data.setLockBeauty(JSONObject.toJSONString(lockList));
                }

                pageantInfo.setPagentDetails(result);
                data.setPaint(JSONObject.toJSONString(result));
                //扣除体力
                if (type == 1) {
                    data = reduceStrength(data, 1);
                } else if(type == 2){
                    data = reduceStrength(data, 4);
                } else {
                    data = reduceStrength(data, 16);
                }
                resultBack.setReward(pageantInfo.getReward());//合成奖励
            } else {
                //判断是否死棋  1.有另外的移动方向 2 没有另外的移动方向
                if (canMove(pageantInfo.getPagentDetails())) {
                    resultBack.setRet(GameErrorCode.E_PAGEANT_CAN_MOVE_OTHER);
                } else {
                    resultBack.setRet(GameErrorCode.E_PAGEANT_CAN_NOT_MOVE);
                }
            }
            resultBack.setUserPageantData(data);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("playGame:" + e);
        }
        return resultBack;
    }


    /**
     * 判断是否需要添加亲密度
     */
    public boolean checkEffectFirstMerge(List<PageantBeautyDetail> lockList, List<PageantDetail> result, UserPageantData data) {
        boolean isAdd = false;
        for (PageantDetail pd : result) {
            for (PageantBeautyDetail lock : lockList) {
                if (pd.getValue() == lock.getBeautyLevel()) {
                    if (!lock.isFirstShow()) {
                        //首次  展示
                        ActivityPageantInfo apInfo = GamePageantMgr.getConfigBeautyMap().get(pd.getValue());
                        String effect = apInfo.getEffectFirstMerge();
                        List<Integer> intimateAndFateList = StringUtils.stringToIntegerList(effect, ";");
                        int intimate = intimateAndFateList.get(0);//亲密度
                        int fate = intimateAndFateList.get(1);//缘分
                        UserBeauty beauty = player.getModule(BeautyModule.class).getBeautyMap().get(data.getBeautyId());
                        if (intimate != 0) {
                            player.getModule(BeautyModule.class).addIntimacy(beauty, intimate, eLogMoneyType.Beauty.getValue(), eLogMoneyType.BeautyPageant.getValue());
                            player.getModule(BeautyModule.class).syncUserBeauty(beauty);
                        }
                        if (fate != 0) {
                            player.getModule(BeautyModule.class).addGlamour(beauty, fate, eLogMoneyType.Beauty.getValue(), eLogMoneyType.BeautyPageant.getValue());
                            player.getModule(BeautyModule.class).syncUserBeauty(beauty);
                        }
                        lock.setFirstShow(true);
                        isAdd = true;
                        break;
                    }
                }
            }
        }
        return isAdd;
    }

    /**
     * 判断是否能移动 true 非死棋  false  死棋
     */
    public boolean canMove(List<PageantDetail> result) {
        if (availableSpace(result).size() != 0) {//
            return true;
        }
        for (int x = 0; x < 4; x++) {
            for (int y = 0; y < 4; y++) {
                PageantDetail t = getDetail(x, y, result);//第一位是行数
                if (t.getValue() != 11) {
                    if ((x < 3 && t.getValue() == getDetail(x + 1, y, result).getValue()) || ((y < 3) && t.getValue() == getDetail(x, y + 1, result).getValue())) {
                        return true;//
                    }
                }
            }
        }
        return false;
    }

    /**
     * 移动方块
     * 原位置
     * 新方向  上1  下2  左3  右4
     */
    public PageantInfo changeData(UserPageantData data, int direction, int activityId) {
        String paintStr = data.getPaint();
        List<PageantDetail> oldPlace = JSONObject.parseArray(paintStr, PageantDetail.class);
        PageantInfo pageantInfo = new PageantInfo();
        if (direction == 3) {
            pageantInfo = left(data, oldPlace, activityId);
        }
        if (direction == 1) {
            pageantInfo = up(data, oldPlace, activityId);
        }
        if (direction == 2) {
            pageantInfo = down(data, oldPlace, activityId);
        }
        if (direction == 4) {
            pageantInfo = right(data, oldPlace, activityId);
        }
        return pageantInfo;
    }

    public PageantInfo right(UserPageantData data, List<PageantDetail> myList, int activityId) {
        myList = rotate(180, myList);
        PageantInfo pageantInfo = left(data, myList, activityId);
        myList = pageantInfo.getPagentDetails();
        myList = rotate(180, myList);
        pageantInfo.setPagentDetails(myList);
        return pageantInfo;
    }

    public PageantInfo up(UserPageantData data, List<PageantDetail> myList, int activityId) {
        myList = rotate(270, myList);
        PageantInfo pageantInfo = left(data, myList, activityId);
        myList = pageantInfo.getPagentDetails();
        myList = rotate(90, myList);
        pageantInfo.setPagentDetails(myList);
        return pageantInfo;
    }

    public PageantInfo down(UserPageantData data, List<PageantDetail> myList, int activityId) {
        myList = rotate(90, myList);
        PageantInfo pageantInfo = left(data, myList, activityId);
        myList = pageantInfo.getPagentDetails();
        myList = rotate(270, myList);
        pageantInfo.setPagentDetails(myList);
        return pageantInfo;
    }

    /**
     * 转换方向
     * params 角度
     */
    private List<PageantDetail> rotate(int angle, List<PageantDetail> myList) {
        String newTitleStr = getNewPaintEmpty();
        List<PageantDetail> newTiles = JSONObject.parseArray(newTitleStr, PageantDetail.class);
        int offsetX = 3, offsetY = 3;
        if (angle == 90) {
            offsetY = 0;
        } else if (angle == 270) {
            offsetX = 0;
        }

        double rad = Math.toRadians(angle);
        int cos = (int) Math.cos(rad);
        int sin = (int) Math.sin(rad);
        for (int x = 0; x < 4; x++) {
            for (int y = 0; y < 4; y++) {
                int newX = (x * cos) - (y * sin) + offsetX;
                int newY = (x * sin) + (y * cos) + offsetY;
                newTiles.set((newX) + (newY) * 4, getDetail(y, x, myList));

            }
        }
        return newTiles;
    }


    /**
     * 向左
     */
    public PageantInfo left(UserPageantData data, List<PageantDetail> myList, int activityId) {
        PageantInfo pageantInfo = new PageantInfo();
        List<PageantDetail> result = new ArrayList<>();
        boolean needAddDetail = false;  //如果两次数据不相同则需要增加新的坐标值
        int sameNum = 0;//相同行数
        StringBuffer rewardBuf = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            List<PageantDetail> line = getLine(i, myList);//获取第一行
            List<PageantDetail> moveLine = moveLeft(line);//向左移动一行
            //合成，新数组为空补0
            List<PageantDetail> merged = mergeLine(moveLine, data, activityId, rewardBuf);//合成一次，新数组为空补0

            result = setLine(i, merged, result);//拷贝到结果集  myTiles

            if (!needAddDetail && !compare(line, merged)) {//结果对比，有合成新数据，需要新增行
                needAddDetail = true;
            }
        }

        if (rewardBuf.length() != 0) {
            List<String> goods = StringUtils.stringToStringList(rewardBuf.toString(), ";");
            Property property = new Property();
            for (String good : goods) {
                List<Integer> idAndNum = StringUtils.stringToIntegerList(good, "=");
                property.addProperty(idAndNum.get(0), BigInteger.valueOf(idAndNum.get(1)));
            }
            player.getModule(CurrencyModule.class).addCurrency(property, eLogMoneyType.Pageant, eLogMoneyType.PageantMergeGetMoney);
            pageantInfo.setReward(rewardBuf.toString());
        }
        pageantInfo.setPagentDetails(result);
        pageantInfo.setChange(needAddDetail);
        return pageantInfo;
    }


    /**
     * 获取第一行
     */
    private List<PageantDetail> getLine(int line, List<PageantDetail> myList) {// 0 1 2 3
        List<PageantDetail> result = new ArrayList<>();//每行四个
        for (int i = 0; i < 4; i++) {
            PageantDetail pageantDetail = getDetail(line, i, myList);
            result.add(pageantDetail);
        }
        return result;
    }

    /**
     * 获取坐标值  x行数  y位置
     */
    private PageantDetail getDetail(int line, int serial, List<PageantDetail> myList) {
        PageantDetail pageantDetail = myList.get(serial + line * 4);
        return pageantDetail;
    }


    /**
     * 向左移动一列
     */
    private List<PageantDetail> moveLeft(List<PageantDetail> oldLine) {
        LinkedList<PageantDetail> l = new LinkedList<PageantDetail>();
        for (int i = 0; i < 4; i++) {
            if (!oldLine.get(i).isEmpty()) {//不为空，组合新队列
                l.add(oldLine.get(i));
            }
        }
        //新数组为空返回旧数组
        if (l.size() == 0) {
            return oldLine;
        } else {
            //新数组
            List<PageantDetail> newLine = new ArrayList<>();
            ensureSize(l, 4);
            for (int i = 0; i < 4; i++) {
                newLine.add(l.removeFirst());
            }
            return newLine;
        }
    }

    /**
     * 新数组为空补0
     */
    private void ensureSize(List<PageantDetail> l, int s) {
        while (l.size() != s) {
            l.add(new PageantDetail());
        }
    }

    /**
     * 合成数据，算法
     */
    private List<PageantDetail> mergeLine(List<PageantDetail> oldLine, UserPageantData data, int activityId, StringBuffer reward) {
        LinkedList<PageantDetail> list = new LinkedList<PageantDetail>();
        for (int i = 0; i < 4 && !oldLine.get(i).isEmpty(); i++) {
            int num = oldLine.get(i).getValue();//值
            if (i < 3 && oldLine.get(i).getValue() == oldLine.get(i + 1).getValue()) {//第一和第二，第二和第三，第三和第四对比，如果相同
                //算法
                if (oldLine.get(i).getValue() != 11 && oldLine.get(i).getValue() != 0) { //最高级不合成
                    //判断两个格子是否有奖励
                    if (oldLine.get(i).getChest() != 0) {
                        reward.append(oldLine.get(i).getGiftBox()).append("=").append(oldLine.get(i).getChest()).append(";");
                    }
                    if (oldLine.get(i + 1).getChest() != 0) {
                        reward.append(oldLine.get(i + 1).getGiftBox()).append("=").append(oldLine.get(i + 1).getChest()).append(";");
                    }
                    //合成
                    num = count(oldLine.get(i).getValue(), activityId, data);//下一等级数据
                    if(num==11){
                        //判断lockbeauty是否展示过，展示过的话加所有等级的亲密度跟缘分
                        elevenLevelReward(data);
                    }
                    i++;//如果两个被选，第二个可以不用循环
                }
                PageantDetail newDetail = new PageantDetail();
                newDetail.setValue(num);
                list.add(newDetail);
            } else {
                PageantDetail newDetail = new PageantDetail();
                newDetail.setValue(num);
                newDetail.setChest(oldLine.get(i).getChest());
                newDetail.setGiftBox(oldLine.get(i).getGiftBox());
                list.add(newDetail);
            }

        }
        if (list.size() == 0) {
            return oldLine;//没有添加新数据返回原来的数据
        } else {
            ensureSize(list, 4);
            return list;
        }
    }

    public void elevenLevelReward(UserPageantData data){
        String lockBeauty = data.getLockBeauty();
        List<PageantBeautyDetail> lockList = JSONObject.parseArray(lockBeauty, PageantBeautyDetail.class);
        for(PageantBeautyDetail lock:lockList){
            if(11==lock.getBeautyLevel()){
                if(lock.isFirstShow()){
                    //所有等级的美女加一遍
                    int intimate = 0;
                    int fate = 0;
                    Map<Integer, ActivityPageantInfo> map = GamePageantMgr.getConfigBeautyMap();
                    for(ActivityPageantInfo apInfo:map.values()){
                        String effect = apInfo.getEffectFirstMerge();
                        List<Integer> intimateAndFateList = StringUtils.stringToIntegerList(effect, ";");
                        intimate = intimate + intimateAndFateList.get(0);//亲密度
                        fate = fate + intimateAndFateList.get(1);//缘分
                    }
                    UserBeauty beauty = player.getModule(BeautyModule.class).getBeautyMap().get(data.getBeautyId());
                    if (intimate != 0) {
                        player.getModule(BeautyModule.class).addIntimacy(beauty, intimate, eLogMoneyType.Beauty.getValue(), eLogMoneyType.BeautyPageant.getValue());
                        player.getModule(BeautyModule.class).syncUserBeauty(beauty);
                    }
                    if (fate != 0) {
                        player.getModule(BeautyModule.class).addGlamour(beauty, fate, eLogMoneyType.Beauty.getValue(), eLogMoneyType.BeautyPageant.getValue());
                        player.getModule(BeautyModule.class).syncUserBeauty(beauty);
                    }
                }
            }
        }

    }


    /**
     * 合成规则,计算分数，返回格子显示的数字  num 显示数值  score 分数
     */
    public int count(int num, int activityId, UserPageantData data) {
        ActivityPageantInfo pageantInfo = GamePageantMgr.getConfigBeautyMap().get(num);
        if (pageantInfo != null) {
            //存在规则
            //计算之后的值
            num = num + 1;
            pageantInfo = GamePageantMgr.getConfigBeautyMap().get(num);
            if (pageantInfo == null) {
                return num - 1;
            }
            //加分数
            int myScore = data.getScore();
            myScore = myScore + pageantInfo.getSorceMerge();
            data.setScore(myScore);
            //更新单场高分
            if(myScore>data.getSingleHighScore()){
                data.setSingleHighScore(myScore);
            }
            //更新总分
            int myHighScroe = data.getHighScore();
            myHighScroe = myHighScroe + pageantInfo.getSorceMerge();
            data.setHighScore(myHighScroe);
            //触发
            player.notifyListener(eGamePlayerEventType.PageantSingleScoreRank.getValue(), myScore);
            player.notifyListener(eGamePlayerEventType.PageantSingleScoreCrossRank.getValue(), myScore);
            player.notifyListener(eGamePlayerEventType.PageantTotalScoreRank.getValue(), data.getHighScore());
            player.notifyListener(eGamePlayerEventType.PageantTotalScoreCrossRank.getValue(), data.getHighScore());

            //加选美币
            if (pageantInfo.getMoneyMerge() > 0) {
                Property property = new Property();
                property.addProperty(GamePageantMgr.getGoodsConfig().getPageantMoneyId(), BigInteger.valueOf(pageantInfo.getMoneyMerge()));
                player.getModule(CurrencyModule.class).addCurrency(property, eLogMoneyType.Pageant, eLogMoneyType.PageantExchangeSynthesis);
                data.setTodayGetMoney(data.getTodayGetMoney() + pageantInfo.getMoneyMerge());
            }
        }
        return num;
    }

    /**
     * 拷贝结果到结果集
     */
    private List<PageantDetail> setLine(int index, List<PageantDetail> re, List<PageantDetail> myList) {
        try {
            for (PageantDetail r : re) {
                myList.add(r);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return myList;
    }

    /**
     * 两个数组对比
     *
     * @param line1
     * @param line2
     * @return
     */
    private boolean compare(List<PageantDetail> line1, List<PageantDetail> line2) {
        if (line1 == line2) {
            return true;
        } else if (line1.size() != line2.size()) {
            return false;
        }

        for (int i = 0; i < line1.size(); i++) {
            if (line1.get(i).getValue() != line2.get(i).getValue()) {
                return false;
            }
        }
        return true;
    }


    //普通场每次移动消耗1点体力,在空白位置生成一个1-3级的美女,有一定概率出现奇异美女
    //高级 固定出现2级美女

    /**
     * 每次合成，新增规则
     *
     * @param addCreateCreate 用于引用带出生成美女需要增加的积分、选美币
     */
    private List<PageantDetail> addTile(int type, List<PageantDetail> myList, List<Integer> addCreateCreate) {
        List<PageantDetail> list = availableSpace(myList);//获取空位置
        if (!availableSpace(myList).isEmpty()) {

            int index = 0 ;
            //如果最大值大于8
            boolean highRandom = false;
            for(PageantDetail my:myList){
                if(my.getValue()>=8){
                    highRandom = true;
                    break;
                }
            }
            if(highRandom&&GamePageantMgr.getWeightOnOff()==1){
                index = getHighRandomIndex(myList);//高级计算
            }else {
                index = (int) (Math.random() * list.size()) % list.size();//获取空位置值
            }
            PageantDetail emptyTime = list.get(index);
            int value = getNum(type);//生成值
            emptyTime.setValue(value);
            //生成宝箱
            emptyTime = getBox(value, emptyTime);
            //计算增加的积分、选美币
            addCreateCreate.add(GamePageantMgr.calcCreateScore(value));
            addCreateCreate.add(GamePageantMgr.calcCreateMoney(value));
        }
        return myList;
    }


    /**
     * 高级计算
     */
    public int getHighRandomIndex(List<PageantDetail> list){
        int index = countAllWeight(list);
        //生成在index位置 转换list位置
        int tempindex = 0;
        for(int i=0;i<index;i++){
            if(list.get(i).getValue()==0){
                tempindex = tempindex+1;
            }
        }
        return tempindex;
    }

    /**
     * 权重总计算
     */
    public int countAllWeight(List<PageantDetail> list){
        Map<Integer, Integer> mapResult = getAllEmptyWeight(list);
        //计算总权重
        int allWeight = 0;
        for (Map.Entry<Integer, Integer> entry : mapResult.entrySet()) {
            allWeight = allWeight+entry.getValue();
        }
        int randomNum = new Random().nextInt(allWeight);
        int indexResult = 0;//随机结果
        int nowPrbablity = 0;//加成概率
        for (Map.Entry<Integer, Integer> entry : mapResult.entrySet()) {
            int tempProbality = nowPrbablity;
            nowPrbablity = nowPrbablity + entry.getValue();
            if (tempProbality <= randomNum && nowPrbablity > randomNum) {
                //命中
                indexResult = entry.getKey();
                break;
            }
        }
        return indexResult;
    }

    /**
     * 计算空盒子的权重
     */
    public static Map<Integer, Integer> getAllEmptyWeight(List<PageantDetail> list) {
        Map<Integer, Integer> allIndexWeightMap = new HashMap<>();
        for (int index = 0; index < list.size(); index++) {
            if (list.get(index).getValue() >= 8) {
                // 触发生成格子策略
                // 遍历每一个有美女的格子
                index = 0;
                for (; index < list.size(); index++) {
                    if (list.get(index).getValue() > 0) {
                        continue;
                    }
                    Map<Integer, Integer> weightMap = getIndexEmptyCellWeight(index, list);
                    for (Map.Entry<Integer, Integer> entry : weightMap.entrySet()) {
                        if (!allIndexWeightMap.containsKey(index)) {
                            allIndexWeightMap.put(index, entry.getValue());
                        }else {
                            allIndexWeightMap.put(index, allIndexWeightMap.get(index) + entry.getValue());
                        }

                    }
                }
                break;
            }
        }
        return allIndexWeightMap;
    }


    /**
     * 每个格子相对于该点的权重map
     * @return
     */
    public static Map<Integer, Integer> getIndexEmptyCellWeight(int index, List<PageantDetail> list) {
        int indexL = index / 4; // 行数
        int indexC = index % 4; // 列数
        Map<Integer, Integer> weight1Length = getWeightByLength(indexL, indexC, list, 1);
        Map<Integer, Integer> weight2Length = getWeightByLength(indexL, indexC, list, 2);
        weight1Length.putAll(weight2Length);
        return weight1Length;
    }

    /**
     * 格子  列表  距离  计算距离的权重map值
     * @param l
     * @param c
     * @param list
     * @param length
     * @return
     */
    public static Map<Integer, Integer> getWeightByLength(int l, int c, List<PageantDetail> list, int length) {
        Map<Integer, Integer> indexWeight = new HashMap<>();
        for (int index = 0; index < list.size(); index++) {
            int targetL = index / 4;
            int targetC = index % 4;
            //获取target value
            //根据value获取权重
            if ((Math.abs(l - targetL) + Math.abs(c - targetC)) == length) {
                int quanzhong = 100;
                if (!indexWeight.containsKey(index)) {
                    if(list.get(index).getValue()!=0){
                        int configWeight = GamePageantMgr.getConfigBeautyMap().get(list.get(index).getValue()).getWeight();
                        if(length==1) {
                            if(0!=configWeight){
                                quanzhong = configWeight;
                            }else {
                                quanzhong = GamePageantMgr.getBaseWeight();
                            }
                        }else {
                            if(0!=configWeight){
                                quanzhong = configWeight/2;
                            }else {
                                quanzhong = GamePageantMgr.getBaseWeight()/2;
                            }
                        }
                    }else {
                        if(length==1){
                            quanzhong = GamePageantMgr.getBaseWeight();
                        }else {
                            quanzhong = GamePageantMgr.getBaseWeight()/2;
                        }
                    }
                    indexWeight.put(index, quanzhong);
                }
            }
        }
        return indexWeight;
    }


    /**
     * 查询有多少个空位
     *
     * @return
     */
    private List<PageantDetail> availableSpace(List<PageantDetail> myList) {
        final List<PageantDetail> list = new ArrayList<PageantDetail>(16);
        for (PageantDetail t : myList) {
            if (t.isEmpty()) {
                list.add(t);
            }
        }
        return list;
    }

    /**
     * 是否生成宝箱
     */
    private PageantDetail getBox(int level, PageantDetail emptyTime) {
        Map<Integer, List<BoxConfig>> map = GamePageantMgr.getConfigBoxMap();
        List<BoxConfig> configs = map.get(level);
        if (configs != null) {
            int randomNum = new Random().nextInt(1000000);//随机数
            int nowPrbablity = 0;
            for (BoxConfig con : configs) {
                int tempProbality = nowPrbablity;
                nowPrbablity = nowPrbablity + con.getProbability();
                if (tempProbality <= randomNum && nowPrbablity > randomNum) {
                    emptyTime.setGiftBox(con.getGoodsId());
                    emptyTime.setChest(con.getNum());
                    break;
                }
            }
        }
        return emptyTime;
    }


    /**
     * 生成随机值   生成带宝箱美女的概率
     */
    private int getNum(int type) {
        //先生成美女，再生成箱子
        int num = 0;
        int randomNum = new Random().nextInt(100);
        int probability11 = 0;
        int probability12 = 0;
        int probability13 = 0;
        if (type == 1) {
            probability11 = GamePageantMgr.getNormalProbabilityConfig().getOneLevel();
            probability12 = GamePageantMgr.getNormalProbabilityConfig().getTwoLevel();
            probability13 = GamePageantMgr.getNormalProbabilityConfig().getThreeLevel();
        } else if (type == 2) {
            probability11 = GamePageantMgr.getHighProbabilityConfig().getOneLevel();
            probability12 = GamePageantMgr.getHighProbabilityConfig().getTwoLevel();
            probability13 = GamePageantMgr.getHighProbabilityConfig().getThreeLevel();
        } else if (type == 3) {
            // 后续加的急速场，换了配置格式
            String[] tmp = GamePageantMgr.getFastProbabilityConfig().split(";");
            int index = RandomHelper.getRandomIndexByWeight(StringUtils.stringToIntegerList(tmp[1], ","));
            return StringUtils.stringToIntegerList(tmp[0], ",").get(index);
        }
        if (randomNum <= probability11&&probability11 !=0) {
            num = 1;
        } else if (randomNum <= probability11 + probability12 && (probability11+probability12)!= 0) {
            num = 2;
        } else if (randomNum <= probability11 + probability12 + probability13) {
            num = 3;
        }
        return num;
    }

//    public Map<Integer, Integer> getAllEmptyWeight(List<PageantDetail> list) {
//        for (int index = 0; index < list.size(); index++) {
//            if (list.get(index).getValue() >= 对应等级) {
//                // 触发生成格子策略
//                // 遍历每一个有美女的格子
//                index = 0;
//                Map<Integer, Integer> allIndexWeightMap = new HashMap<>();
//                for (; index < list.size(); index++) {
//                    if (list.get(index).getValue() <= 0) {
//                        continue;
//                    }
//                    Map<Integer, Integer> weightMap = getIndexEmptyCellWeight(index, list);
//                    for (Map.Entry<Integer, Integer> entry : weightMap.entrySet()) {
//                        if (!allIndexWeightMap.containsKey(entry.getKey())) {
//                            allIndexWeightMap.put(entry.getKey(), 0);
//                        }
//                        allIndexWeightMap.put(entry.getKey(), allIndexWeightMap.get(entry.getKey()) + entry.getValue());
//                    }
//                }
//                return allIndexWeightMap;
//            }
//        }
//    }
//
//    public Map<Integer, Integer> getIndexEmptyCellWeight(int index, List<PageantDetail> list) {
//
//        int indexL = index / 4; // 行数
//        int indexC = index % 4; // 列数
//
////        PageantDetail[][] pageantDetailxy = new PageantDetail[4][4];
////        for (int l = 0; l < 4; l++) { // i 行数
////            for (int c = 0; c < 4; c++) { //j 列数
////                pageantDetailxy[l][c] = list.get(l * 4 + c);
////            }
////        }
//        Map<Integer, Integer> weight1Length = getWeightByLength(indexL, indexC, list, 1);
//        Map<Integer, Integer> weight2Length = getWeightByLength(indexL, indexC, list, 2);
//        weight1Length.putAll(weight2Length);
//        return weight1Length;
//    }
//
//    public Map<Integer, Integer> getWeightByLength(int l, int c, List<PageantDetail> list, int length) {
//        Map<Integer, Integer> indexWeight = new HashMap<>();
//        for (int index = 0; index < list.size(); index++) {
//            if (list.get(index).getValue() == 0) {
//                int targetL = index / 4;
//                int targetC = index % 4;
//                if ((Math.abs(l - targetL) + Math.abs(c - targetC)) == length) {
//                    if (!indexWeight.containsKey(index)) {
//                        indexWeight.put(index, 0);
//                    }
//                    indexWeight.put(index, indexWeight.get(index) + 权重值);
//                }
//            }
//        }
//    }


    /**
     * 游戏结算(主动)
     */
    public UserPageantDataResult settlementBeautyActivity(int activityId) {
        UserPageantDataResult result = new UserPageantDataResult();

        ActivityInfo activityInfo = GamePageantMgr.getActivityInfo();
        if (activityInfo == null) {
            result.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return result;
        }

        UserPageantData data = getUserPageantData(activityId);
        if (null == data || data.getBeautyId() == 0) {
            result.setRet(GameErrorCode.E_PAGEANT_HAD_SETTLEMENT);
            return result;
        }

        List<PageantDetail> detailList = JSONObject.parseArray(data.getPaint(), PageantDetail.class);
        if (ActivityMgr.activityInTime(activityInfo) && canMove(detailList)) {
            result.setRet(GameErrorCode.E_PAGEANT_CAN_MOVE_OTHER);
            return result;
        }

        result.setRet(0);
        result.setEvaluation("");//清空旧评价
        result.setScore(data.getScore());
        int oldBeautyId = data.getBeautyId();
//        if (data.getScore() > data.getSingleHighScore()) {
//            data.setSingleHighScore(data.getScore());//单场最高
//        }
        int score = data.getScore();
//        int highScore = data.getHighScore();
//        data.setHighScore(score + highScore);//历史总分
        data.setPaint(getNewPaint());
        data.setBeautyId(0);
        data.setScore(0);
        data.setLastUpdateTime(new Date().getTime());
        String newLockBeauty = getNewLockBeauty();
        data.setLockBeauty(newLockBeauty);
        data.setGoodsTimes(GamePageantMgr.getGoodsTimesChongPai() + "|" + GamePageantMgr.getGoodsTimesXiaochu());
        //添加评价
        String desc = "";
        List<DescConfig> descConfigs = GamePageantMgr.getDescConfig();
        for (int i = 0; i < descConfigs.size(); i++) {
            int num = descConfigs.get(i).getScore();
            if (num <= score) {
                desc = ServerLanguageMgr.getContent(descConfigs.get(i).getDescription(), player.getUserInfo().getLanguage());
            } else {
                break;
            }
        }
        result.setEvaluation(desc);
        result.setOldBeautyId(oldBeautyId);
        result.setUserPageantData(data);
        return result;
    }


    /**
     * 初始化加载美女解锁状态
     *
     * @return
     */
    private String getNewLockBeauty() {
        List<PageantBeautyDetail> lockList = new ArrayList<>();
        for (int level : GamePageantMgr.getConfigBeautyMap().keySet()) {
            PageantBeautyDetail detail1 = new PageantBeautyDetail();
            detail1.setBeautyLevel(level);
            if (level == 1) {
                detail1.setFirstShow(true);
            } else {
                detail1.setFirstShow(false);
            }
            lockList.add(detail1);
        }
        return JSONArray.toJSONString(lockList);
    }


    /**
     * 初始化16格数据
     */
    private String getNewPaint() {
        List<PageantDetail> newList = getEmptyPaintList();
        newList.get(9).setValue(1);
        newList.get(10).setValue(1);
        newList.get(13).setValue(1);
        newList.get(14).setValue(1);
        return JSONArray.toJSONString(newList);
    }

    /**
     * @return
     */
    public List<PageantDetail> getEmptyPaintList() {
        List<PageantDetail> newList = new ArrayList<>();
        for (int i = 0; i < 16; i++) {
            PageantDetail detail1 = new PageantDetail();
            detail1.setValue(0);//美女等级
            detail1.setChest(0);//是否特殊 0 普通  1 特殊
            newList.add(detail1);

        }
        return newList;
    }

    /**
     * 初始化16格数据空数据
     */
    public String getNewPaintEmpty() {
        List<PageantDetail> newList = getEmptyPaintList();
        return JSONArray.toJSONString(newList);
    }


    /**
     * 道具使用
     */
    public UserPageantDataResult useGood(int activityId, int goodsId, int pramsFirst) {
        UserPageantDataResult result = new UserPageantDataResult();
        UserPageantData userPageantData = getUserPageantData(activityId);
        result.setRet(0);
        try {
            GoodsConfig goodsConfig = GamePageantMgr.getGoodsConfig();
            String goodsTimes = userPageantData.getGoodsTimes();

            if (StringUtils.isNullOrEmpty(goodsTimes)) {
                goodsTimes = GamePageantMgr.getGoodsTimesChongPai() + "|" + GamePageantMgr.getGoodsTimesXiaochu();
                userPageantData.setGoodsTimes(goodsTimes);
            }
            List<Integer> goodTime = StringUtils.stringToIntegerList(goodsTimes, "\\|");
            int chongpaiTime = goodTime.get(0);
            int xiaochuTime = goodTime.get(1);
            if (goodsConfig.getPageantRearrange() == goodsId) {
                //重排
                if (checkGoods(goodsId, 1)) {
                    if (chongpaiTime < 1) {
                        result.setRet(GameErrorCode.E_PAGEANT_GOODS_USE_ERROR);
                        return result;
                    }

                    String paint = chongpai(userPageantData.getPaint());
                    if (paint.equals(userPageantData.getPaint())) {
                        result.setRet(GameErrorCode.E_PAGEANT_PAINT_NOT_CHANGE);
                        return result;
                    }

                    if (!reduceGoodsNum(goodsId, 1)) {
                        result.setRet(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
                        return result;
                    }

                    chongpaiTime = chongpaiTime - 1;
                    goodsTimes = chongpaiTime + "|" + xiaochuTime;
                    userPageantData.setGoodsTimes(goodsTimes);

                    userPageantData.setPaint(paint);

                } else {
                    //道具数量不足
                    result.setRet(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
                    return result;
                }
            } else if (goodsConfig.getPageantMurder() == goodsId) {
                //消除
                if (checkGoods(goodsId, 1)) {
                    if (xiaochuTime < 1) {
                        result.setRet(GameErrorCode.E_PAGEANT_GOODS_USE_ERROR);
                        return result;
                    }

                    List<PageantDetail> details = JSONObject.parseArray(userPageantData.getPaint(), PageantDetail.class);
                    //判断使用消除的格子是不是空的
                    if(pramsFirst < 0 || pramsFirst >= details.size()){
                        result.setRet(GameErrorCode.E_PAGEANT_GOODS_USE_ERROR);
                        return result;
                    }
                    PageantDetail pageant = details.get(pramsFirst);
                    if(pageant.getValue() == 0){
                        result.setRet(GameErrorCode.E_PAGEANT_GOODS_USE_ERROR);
                        return result;
                    }
                    //判断是否只剩下一个
                    int count = 0;
                    for (PageantDetail detail : details) {
                        if (detail.getValue() != 0) {
                            count = count + 1;
                            if (count > 2) {
                                //可以消除
                                break;
                            }
                        }
                    }
                    if (count == 1) {
                        //只剩一个格子，无法消除
                        result.setRet(GameErrorCode.E_PAGEANT_PAINT_ONE_ONLY);
                        return result;
                    }

                    if (!reduceGoodsNum(goodsId, 1)) {
                        result.setRet(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
                        return result;
                    }

                    xiaochuTime = xiaochuTime - 1;
                    goodsTimes = chongpaiTime + "|" + xiaochuTime;
                    userPageantData.setGoodsTimes(goodsTimes);


                    String paint = xiaochu(activityId, userPageantData.getPaint(), pramsFirst);
                    userPageantData.setPaint(paint);
                } else {
                    //道具数量不足
                    result.setRet(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
                    return result;
                }
            } else if (goodsConfig.getRestoreStrength() == goodsId) {
                //增加体力
                if (checkGoods(goodsId, pramsFirst)) {
                    int newStrength = 100 * pramsFirst;
                    if (reduceGoodsNum(goodsId, pramsFirst)) {
                        reduceStrength(userPageantData, -newStrength);//加体力用负数
                    } else {
                        //道具使用失败
                        result.setRet(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
                        return result;
                    }
                } else {
                    //道具数量不足
                    result.setRet(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
                    return result;
                }
            } else {
                //道具不对
                result.setRet(GameErrorCode.E_BAG_ITEM_CAN_NO_USE);
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("useGood:" + e);
        }
        result.setUserPageantData(userPageantData);
        return result;
    }

    /**
     * 道具充足判断
     */
    private boolean checkGoods(int goodsId, int goodsNum) {
        Property property = new Property();
        property.addProperty(goodsId, BigInteger.valueOf(goodsNum));
        boolean bo = player.getModule(CurrencyModule.class).currencyIsEnough(property);
        return bo;
    }

    /**
     * 扣除道具
     */
    private boolean reduceGoodsNum(int goodsId, int goodsNum) {
        Property property = new Property();
        property.addProperty(goodsId, BigInteger.valueOf(goodsNum));
        boolean bo = player.getModule(CurrencyModule.class).removeCurrency(property, eLogMoneyType.Activity, eLogMoneyType.PageantExchangeShop);
        return bo;
    }


    /**
     * 重排
     */
    public String chongpai(String paint) {
        List<PageantDetail> oldPlace = JSONObject.parseArray(paint, PageantDetail.class);
        List<PageantDetail> tempPlace = JSONObject.parseArray(paint, PageantDetail.class);
        //details根据values大小排序
        Collections.sort(oldPlace, new Comparator<PageantDetail>() {
            @Override
            public int compare(PageantDetail o1, PageantDetail o2) {
                if (o2.getValue() > o1.getValue()) {
                    return 1;
                } else if (o2.getValue() == o1.getValue()) {
                    return 0;
                } else {
                    return -1;
                }
            }
        });
        List<PageantDetail> newPlace = new ArrayList<>();
        newPlace.add(oldPlace.get(0));
        newPlace.add(oldPlace.get(1));
        newPlace.add(oldPlace.get(2));
        newPlace.add(oldPlace.get(3));
        newPlace.add(oldPlace.get(7));
        newPlace.add(oldPlace.get(6));
        newPlace.add(oldPlace.get(5));
        newPlace.add(oldPlace.get(4));
        newPlace.add(oldPlace.get(8));
        newPlace.add(oldPlace.get(9));
        newPlace.add(oldPlace.get(10));
        newPlace.add(oldPlace.get(11));
        newPlace.add(oldPlace.get(15));
        newPlace.add(oldPlace.get(14));
        newPlace.add(oldPlace.get(13));
        newPlace.add(oldPlace.get(12));
        //判断值是否发生改变，如果没有改变返回原来的值
        for(int i=0;i<16;i++){
            if(tempPlace.get(i).getValue()!=newPlace.get(i).getValue()){
                //不等于为新值
                String afterDataStr = JSONArray.toJSONString(newPlace);
                return afterDataStr;
            }
        }
        return paint;
    }


    /**
     * 消除
     */
    public String xiaochu(int activityId, String paint, int target) {
        List<PageantDetail> oldPlace = JSONObject.parseArray(paint, PageantDetail.class);
        PageantDetail pageant = oldPlace.get(target);
        AutoLogMgr.add(new LogPageantClearLog(activityId, player.getUserId(), pageant.getValue()));
        pageant.setValue(0);
        pageant.setChest(0);
        pageant.setGiftBox(0);
        String afterDataStr = JSONArray.toJSONString(oldPlace);
        return afterDataStr;
    }


    /**
     * 更新用户体力  减少体力数
     */
    public UserPageantData reduceStrength(UserPageantData data, int num) {
        long nowTime = System.currentTimeMillis();
        int nowStrength = data.getPhysicalStrength();
        int newStrength = nowStrength - num;
        data.setPhysicalStrength(newStrength);
        data.setLastUpdateTime(nowTime);
        long oldRefreshTime = data.getStrengthTime();
        int maxStrength = GamePageantMgr.getStrengthConfig().getMaxStrength();
        if (nowStrength >= maxStrength && newStrength < maxStrength) {
            data.setStrengthTime(nowTime);
        }

        //发送协议
        PageantProto.PageantRefreshStrengthMsg.Builder respMsg = PageantProto.PageantRefreshStrengthMsg.newBuilder();
        respMsg.setStrength(newStrength);
        respMsg.setNextRefreshTime(data.getStrengthTime() / 1000);
        player.sendPacket(Protocol.U_PAGEANT_REFRESH_STRENGTH, respMsg);

        return data;
    }


    /**
     * 获取美女图鉴
     */
    public List<BeautyConfig> getPicture() {
        List<BeautyConfig> beautyConfigs = new ArrayList<>();
        Map<Integer, ActivityPageantInfo> configBeautyMap = GamePageantMgr.getConfigBeautyMap();
        for (ActivityPageantInfo configBeauty : configBeautyMap.values()) {
            BeautyConfig beauty = new BeautyConfig();
            beauty.setLevel(configBeauty.getLevel());
            beauty.setBeautyName(ServerLanguageMgr.getContent(configBeauty.getName(), player.getUserInfo().getLanguage()));
            beauty.setBeautyDesc(ServerLanguageMgr.getContent(configBeauty.getDesc(), player.getUserInfo().getLanguage()));
            String firstEffect = configBeauty.getEffectFirstMerge();
            String[] intimateAndFate = firstEffect.split(";");
            beauty.setIntimate(Integer.valueOf(intimateAndFate[0]));
            beauty.setFate(Integer.valueOf(intimateAndFate[1]));
            beauty.setScore(configBeauty.getSorceMerge());
            beauty.setMoney(configBeauty.getMoneyMerge());
            beautyConfigs.add(beauty);
        }
        return beautyConfigs;
    }

    /**
     * 排名详情
     */
    public RankingDetailsResult getRankingDetails(int activityId) {
        RankingDetailsResult result = new RankingDetailsResult();
        result.setRet(0);
        UserPageantData data = getUserPageantData(activityId);
        if (data != null) {
            ActivityInfo openActivityInfo = NormalActivityMgr.getActivityInfo(activityId);
            List<ActivityConditionInfo> conditions = NormalActivityMgr.getActivityConditionInfoList(activityId);
            if (null != openActivityInfo&&conditions!=null&&conditions.size()>0) {
                Boolean isCross=false;
                if(conditions.get(0).getType()==eGamePlayerEventType.PageantSingleScoreRank.getValue() ||conditions.get(0).getType()==eGamePlayerEventType.PageantTotalScoreRank.getValue()){
                    isCross = false;
                }else {
                    isCross = true;
                }
                //78 单局 79 总分 本服  80 单局 81 总分 跨服
                if(isCross){//跨服活动
                    result.setNeedCross(true);
                }else {
                    RankListModel rankListModel = ActivityRankMgr.getActivityRankListModel(activityId,  eGamePlayerEventType.PageantSingleScoreRank.getValue());//单场
                    if (null != rankListModel) {
                        int ranking = rankListModel.unlockGetMyRank(player.getUserId());
                        result.setRecordRanking(ranking);
                        //获取距离上一名  -1未上榜
                        if(ranking!=1&&ranking!=-1){
                            int rankingNext = ranking-1;//上一名排名
                            BigInteger rankingNextValue = rankListModel.getRankList().get(rankingNext-1).getValue();//获取上一名排名分数
                            BigInteger myValue = rankListModel.getRankList().get(ranking-1).getValue();//获取我的分数
                            result.setNextRecordRanking(rankingNextValue.subtract(myValue).intValue());
                        }else {
                            //第一名
                            result.setNextRecordRanking(-1);
                        }
                    }else {
                        result.setNextRecordRanking(-1);//没有排行榜数据
                    }
                    RankListModel rankListModelAll = ActivityRankMgr.getActivityRankListModel(activityId, eGamePlayerEventType.PageantTotalScoreRank.getValue());//总分
                    if (null != rankListModelAll) {
                        int rankingAll = rankListModelAll.unlockGetMyRank(player.getUserId());
                        result.setTotalRanking(rankingAll);
                        //获取距离上一名
                        if(rankingAll!=1&&rankingAll!=-1){
                            int rankingNextAll = rankingAll-1;//上一名排名
                            BigInteger rankingNextValueAll = rankListModelAll.getRankList().get(rankingNextAll-1).getValue();//获取上一名排名分数
                            BigInteger myValueAll = rankListModelAll.getRankList().get(rankingAll-1).getValue();//获取我的分数
                            result.setNextTotalRanking(rankingNextValueAll.subtract(myValueAll).intValue());
                        }else {
                            //第一名
                            result.setNextTotalRanking(-1);
                        }
                    }else {
                        result.setNextTotalRanking(-1);
                    }
                }
            }else {
                result.setRecordRanking(-1);
                result.setTotalRanking(-1);
            }
            result.setBeautyId(data.getBeautyId());
            result.setTotalScore(data.getHighScore());
            result.setRecordScore(data.getSingleHighScore());
        } else {
            //没结算过没排名
            result.setBeautyId(0);
            result.setTotalScore(0);
            result.setTotalRanking(-1);
            result.setNextTotalRanking(0);
            result.setRecordScore(0);
            result.setRecordRanking(-1);
            result.setNextRecordRanking(0);
        }
        return result;
    }


    /**
     * 定时器增加体力  移动和初始化改变体力
     */
    public void addPower(UserPageantData data) {
        long time = System.currentTimeMillis();
        StrengthConfig sc = GamePageantMgr.getStrengthConfig();
        int between = sc.getSecends();//间隔秒数
        int addStrength = sc.getAddStrength();//增加体力数
        int maxStrength = sc.getMaxStrength();//最大值

        if (null != data) {
            long strengthTime = time - data.getStrengthTime();
            //相差秒数 20分钟  1200秒
            long second = strengthTime / 1000;//上次更新时间和当前时间相差的秒数
            if (second > between) {
                //查看间隔秒数是周期的多少倍
                long mo = 1l;
                if (between != 0) {
                    mo = second / between;
                }
                if (data.getPhysicalStrength() + addStrength * mo > maxStrength) {
                    if (data.getPhysicalStrength() > maxStrength) {
                        addStrength(data, 0, time);
                    } else {
                        int num = maxStrength - data.getPhysicalStrength();
                        addStrength(data, num, time);
                    }
                } else {
                    int num = addStrength * Integer.valueOf(String.valueOf(mo));
                    addStrength(data, num, time);
                }
            }
        }
    }


    /**
     * 更新用户体力  加体力数(移动的时候判断是否到加体力时间)
     */
    public UserPageantData addStrength(UserPageantData data, int num, long time) {
        StrengthConfig sc = GamePageantMgr.getStrengthConfig();
        int between = sc.getSecends();//间隔秒数
        long strengthTime = time - data.getStrengthTime();
        long second = strengthTime / 1000;//上次更新时间和当前时间相差的秒数
        long mo = 1l;
        if (between != 0) {
            mo = second / between;
        }

        int nowStrength = data.getPhysicalStrength();
        int newStrength = nowStrength + num;
        data.setPhysicalStrength(newStrength);
        long oldRefreshTime = data.getStrengthTime();
        long addTime = GamePageantMgr.getStrengthConfig().getSecends() * 1000 * mo + oldRefreshTime;
        data.setStrengthTime(addTime);
        data.setLastUpdateTime(time);
        int maxStrength = GamePageantMgr.getStrengthConfig().getMaxStrength();
        if (nowStrength >= maxStrength && newStrength < maxStrength) {
            data.setStrengthTime(time);
        }

        //发送协议
        PageantProto.PageantRefreshStrengthMsg.Builder respMsg = PageantProto.PageantRefreshStrengthMsg.newBuilder();
        respMsg.setStrength(newStrength);
        respMsg.setNextRefreshTime(addTime / 1000);
        player.sendPacket(Protocol.U_PAGEANT_REFRESH_STRENGTH, respMsg);
        return data;
    }

    /**
     * 自动消耗活动道具
     * @param activityInfo
     */
    public void autoUseActivityGoods(ActivityInfo activityInfo){
        if(ActivityMgr.activityInShowPeriod(activityInfo) || ActivityMgr.activityInRewardPeriod(activityInfo)){//在展示期或者领奖期
          /*  List<Integer> paramList = StringUtils.stringToIntegerList(activityInfo.getParam6(), "\\|");
            BagModule bagModule = player.getModule(BagModule.class);
            bagModule.removePageantActivityBagItem(activityInfo, paramList.get(0), paramList.get(1));   //重排道具
            bagModule.removePageantActivityBagItem(activityInfo, paramList.get(0), paramList.get(2));   //消除道具
            bagModule.removePageantActivityBagItem(activityInfo, paramList.get(0), paramList.get(3));   //体力恢复道具*/
        }
    }

    /**
     * 加积分、选美币
     */
    public void addScoreAndMoney(UserPageantData data, int scoreCount, int moneyCount) {
        // 【选美币】
        Property property = new Property();
        property.addProperty(GamePageantMgr.getGoodsConfig().getPageantMoneyId(), BigInteger.valueOf(moneyCount));
        player.getModule(CurrencyModule.class).addCurrency(property, eLogMoneyType.Pageant, eLogMoneyType.PageantCreateGetMoney);

        // 【积分】
        //加分数
        int myScore = data.getScore();
        myScore = myScore + scoreCount;
        data.setScore(myScore);
        //更新单场高分
        if (myScore > data.getSingleHighScore()) {
            data.setSingleHighScore(myScore);
        }
        //更新总分
        int myHighScroe = data.getHighScore();
        myHighScroe = myHighScroe + scoreCount;
        data.setHighScore(myHighScroe);
        //触发
        player.notifyListener(eGamePlayerEventType.PageantSingleScoreRank.getValue(), myScore);
        player.notifyListener(eGamePlayerEventType.PageantSingleScoreCrossRank.getValue(), myScore);
        player.notifyListener(eGamePlayerEventType.PageantTotalScoreRank.getValue(), data.getHighScore());
        player.notifyListener(eGamePlayerEventType.PageantTotalScoreCrossRank.getValue(), data.getHighScore());
    }

}
